package com.leetcode.algorithm.y21.m01;

import java.util.LinkedList;
import java.util.Queue;

/**
 * leetcode-cn.com 
 * (done)279. 完全平方数
 * 
 * @author jie.deng
 * @date 2021/01/11
 */
public class MySolution0111 {

    /**
     * 
     * 给定正整数 n，找到若干个完全平方数（比如 1, 4, 9, 16, ...）使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
     * 
     * 示例 1:
     * 
     * 输入: n = 12
     * 输出: 3 
     * 解释: 12 = 4 + 4 + 4.
     * 示例 2:
     * 
     * 输入: n = 13
     * 输出: 2
     * 解释: 13 = 4 + 9.
     * 
     * 来源：力扣（LeetCode）
     * 链接：https://leetcode-cn.com/problems/perfect-squares
     * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
     * 
     * @param n
     * @return
     */
    public int numSquares(int n) {
        Queue<Integer> queue = new LinkedList<>(); // store all nodes which are waiting to be processed
        int step = 0;// number of steps neeeded from root to current node

        // initialize
        queue.add(n);

        // BFS
        while (!queue.isEmpty()) {
            step++;
            // iterate the nodes which are already in the queue
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                // 
                Integer cur = queue.poll();
                for (int j = 1; j * j <= cur; j++) {
                    int remain = cur - j * j;
                    if (remain == 0) {
                        return step;
                    }
                    queue.offer(remain);
                }
            }
        }
        return -1;// there is no path from root to target
    }
    
    public int numSquares2(int n) {
        int dp[] = new int[n + 1];
        dp[0] = 0;
        for (int i = 1; i * i <= n; i++) {
            dp[i * i] = 1;
        }
        if (dp[n] != 0) {
            return dp[n];
        }
        for (int i = 2; i <= n; i++) {
            if (dp[i] == 0) {
                // 计算nums[i] = Math.min(nums[1]+nums[i-1], nums[2]+nums[i-2], nums[3]+nums[i-3], ...);
                int j = 1;
                int minNum = dp[j] + dp[i - j];
                int mid = i / 2 + 1;
                for (j = 2; j < mid; j++) {
                    int tmp = dp[j] + dp[i - j];
                    if (tmp < minNum) {
                        minNum = tmp;
                    }
                }
                dp[i] = minNum;
            }
        }
        return dp[n];
    }
    
    public int numSquares3(int n) {
        int[] dp = new int[n + 1]; // 默认初始化值都为0
        for (int i = 1; i <= n; i++) {
            dp[i] = i; // 最坏的情况就是每次+1
            for (int j = 1; i - j * j >= 0; j++) {
                dp[i] = Math.min(dp[i], dp[i - j * j] + 1); // 动态转移方程
            }
        }
        return dp[n];
    }
    
}
